package com.scholarship.system.controller;

import com.scholarship.system.common.dto.Result;
import com.scholarship.system.entity.User;
import com.scholarship.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户个人信息
     */
    @GetMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    public Result<User> getCurrentUserProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        log.info("获取用户个人信息: username={}, authorities={}", username, authentication.getAuthorities());

        User user = userService.getByUsername(username);
        if (user == null) {
            log.error("未找到用户: {}", username);
            return Result.error("用户不存在");
        }

        return Result.success(user);
    }

    /**
     * 更新当前用户个人信息
     */
    @PutMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> updateCurrentUserProfile(@Valid @RequestBody User user) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        log.info("更新用户个人信息: username={}, authorities={}", username, authentication.getAuthorities());

        User currentUser = userService.getByUsername(username);
        if (currentUser == null) {
            log.error("未找到用户: {}", username);
            return Result.error("用户不存在");
        }

        // 只允许更新自己的信息，且不能修改角色
        user.setId(currentUser.getId());
        user.setUsername(currentUser.getUsername());
        user.setRole(currentUser.getRole());

        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 以下接口仅管理员可访问
     */

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<List<User>> list(@RequestParam(required = false) String role,
            @RequestParam(required = false) String keyword) {
        return Result.success(userService.getUserList(role, keyword));
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> add(@Valid @RequestBody User user) {
        userService.addUser(user);
        return Result.success();
    }

    /**
     * 更新用户
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> update(@Valid @RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> delete(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success();
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPassword/{id}")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> resetPassword(@PathVariable Long id) {
        userService.resetPassword(id);
        return Result.success();
    }
}